import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Image, Text, Input } from '@tarojs/components';
import { AtInputNumber } from 'taro-ui';
import {newHttp} from "../../utils/request";
import {
	TARO_ENV,
	GOODS_DETAIL_PRE_ORDER_TT,
	GOODS_INFO_PRODUCT_LIST_TT,
	CHECK_CALENDAR_DATE_TT,
	GOODS_INFO_PRODUCT_CALENDAR_TT,
	APPOINTMENT_PRODUCT_DETAIL_TT,
	CONFIRM_APPOINTMENT_TT
} from '../../constants/api';
import {GetRequest, deepClone} from '../../utils/tools';
import calendarObj from "../../utils/calendar";
import classnames from 'classnames';
import Float from "../../components/float/float";
import CalendarPage from "../../components/appointment/calendar";
import './appointment.scss';

export default class AppointmentMake extends Component {
	constructor(props) {
		super(props);
		this.state = {
			showLoading: true,
			limitStart: "",
			limitEnd: "",
			preGoodData: {},
			appointmentId: "",
			order_id: "",
			orderUuid: "",
			uuid: "",
			goodsUuid: "",
			calculating: false,
			calendarData: [],
			goodsProductList: [],
			goodsProductDetail: {},
			goodsProductDate: [],
			goodProductUuid: "",
			dayInfoLimit: {},
			appointmentInfo: {
				goodId: "",
				currentDate: [],
				num: 1,
				buy_num_min: 1,
				buy_num_max: 1,
				code: "",
				linkman: "",
				phone: "",
				identity_num: "",
				remark: "",
			},
			timeParams: {
				year: true,
				month: true,
				day: true,
				hour: false,
				minute: false,
				second: false
			},
			appointmenting: false,
			dateChecking: false
		};
	}

	componentDidMount() {
		const { id, uuid, goodsUuid, appointmentId } = Taro.getCurrentInstance().router.params;
		const limitStart = calendarObj.getDatetimeAfterSomeDatetime(null, 30); // 当前时间30分钟之后
		const limitEnd = calendarObj.getDatetimeAfterSomeDatetime(limitStart, 30); // 开始时间30分钟之后
		this.setState({
			appointmentId: appointmentId,
			order_id: id,
			uuid: uuid,
			goodsUuid: goodsUuid,
			limitStart,
			limitEnd
		})
	}
	async componentDidShow() {
		await Taro.setNavigationBarTitle({
            title: '预约表单'
        })
		Taro.showLoading({
			title: "请稍等..."
		});
		this.getPreOrderDetail(this.state.uuid);
		this.getProductList(this.state.goodsUuid);
		this.getCalendar("32513sd5f3sd2f1s3d2");
	}

	// choose good
	handleChooseGood(good) {
		this.setState(state => ({
			goodProductUuid: good.uuid,
			appointmentInfo: {
				...state.appointmentInfo,
				goodId: good.id
			}
		}), () => {
			this.getCalendar(this.state.goodProductUuid);
		});
	}
	// 确定日历
	handleSureDate = ({ date }) => {
		console.log("确定日历 : ", date);
		if(this.state.dateChecking) return;

		if(date.length > 0) {
			Taro.showLoading({
				title: "请稍等..."
			});
			this.setState(state => ({
				dateChecking: true,
				appointmentInfo: {
					...state.appointmentInfo,
					currentDate: state.appointmentInfo.currentDate.splice(0)
				}
			}), () => {
				this.setState(state => ({
					appointmentInfo: {
						...state.appointmentInfo,
						currentDate: date
					}
				}), () => {
					const appointmentDateRange = {
						start: this.state.appointmentInfo.currentDate[0],
						end: this.state.appointmentInfo.currentDate.slice(-1)[0],
						range: [...this.state.appointmentInfo.currentDate],
					};
					this.getCheckDates(JSON.stringify(appointmentDateRange));
				});
			});
		}else {
			this.setState(state => ({
				appointmentInfo: {
					...state.appointmentInfo,
					currentDate: state.appointmentInfo.currentDate.splice(0)
				},
				dateChecking: false
			}))
		}
	}

	// detail pre order
	async getPreOrderDetail(uuid) {
		const resGood = await newHttp.catchGet(GOODS_DETAIL_PRE_ORDER_TT, { uuid });

		if(resGood) {
			this.setState({ preGoodData: resGood.data });
		}
	}
	// 获取可预约单品
	async getProductList(uuid) {
		const res = await newHttp.catchGet(GOODS_INFO_PRODUCT_LIST_TT, { uuid });
		if(res) {
			this.setState({ goodsProductList: res || [] });
			// 默认取第1个单品
			if(res.length > 0) {
				this.setState(state => ({
					goodProductUuid: res.data[0].uuid,
					appointmentInfo: {
						...state.appointmentInfo,
						goodId: res.data[0].id
					}
				}), () => {
					this.getCalendar(this.state.goodProductUuid);
				});
			}
		}
	}
	// 获取日历
	async getCalendar(goodsUuid) {
		Taro.showLoading({
			title: "请稍等..."
		});
		const resData = await newHttp.catchGet(GOODS_INFO_PRODUCT_CALENDAR_TT, { goodsUuid });

		if(resData) {
			const calendarData = resData.data;
			this.setState({ calendarData });

			// 获取预约产品详情
			const res = await newHttp.catchGet(APPOINTMENT_PRODUCT_DETAIL_TT, { uuid: this.state.appointmentId });
			if(res) {
				const detailData = res.data;
				this.setState(state => ({
					goodsProductDetail: detailData,
					appointmentInfo: {
						...state.appointmentInfo,
						currentDate: [] // 初始化|清空
					}
				}));

				const temp_currentDate = [];
				const { late_num } = detailData; // 住几晚
				const startDate = calendarData[0].date;
				temp_currentDate.push(startDate);
				// 根据入住几晚计算日期范围(如果第一天后面是周末<无价格>该怎么取)
				if(res.data.goods_type === 2) {
					for(let i = 0; i < late_num; i++) {
						const endDate = calendarObj.getDateByDate(calendarObj.getCurrentDate(), i + 1);
						temp_currentDate.push(endDate);
					}
				}

				this.setState(state => ({
					appointmentInfo: {
						...state.appointmentInfo,
						currentDate: temp_currentDate
					}
				}), () => {
					const appointmentDateRange = {
						start: startDate,
						end: temp_currentDate.slice(-1)[0],
						range: [...temp_currentDate],
					};
					this.getCheckDates(JSON.stringify(appointmentDateRange));
				});
			}
		}
	}
	// 获取日期是否可选
	async getCheckDates(appointmentDateRange) {
		const params = {
			order_uuid: this.state.uuid,
			uuid: this.state.appointmentId,
			appointmentDateRange,
			goods_uuid: this.state.goodProductUuid
		};
		const res = await newHttp.catchGet(CHECK_CALENDAR_DATE_TT, params);

		if(res) {
			if(res.data.max_amount === 0) {
				this.setState(state => ({
					appointmentInfo: {
						...state.appointmentInfo,
						currentDate: state.appointmentInfo.currentDate.splice(0)
					}
				}));
				Taro.showModal({
					content: "没有可预约的天数，请重新选择",
					showCancel: false,
					confirmText: "知道了"
				});
				return;
			}

			this.setState(state => ({
				dayInfoLimit: res.data,
				dateChecking: false,
				appointmentInfo: {
					...state.appointmentInfo,
					buy_num_max: res.data.max_amount,
					code: res.data.ticket
				}
			}), () => {
				Taro.hideLoading();
			})
		}else {
			this.setState({ dateChecking: false });
		}
	}

	// 立即预约
	async appointmentNow() {
		const { appointmentId, appointmentInfo, goodProductUuid, goodsProductDetail } = this.state;
		const phoneReg = /^1[0-9]{10}$/;
		const idcardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;

		if(appointmentInfo.currentDate.length === 0) {
			Taro.showToast({
				title: "请选择日期",
				icon: "none"
			});
			return;
		}
		if(!appointmentInfo.code) {
			Taro.showToast({
				title: "请输入预约码",
				icon: "none"
			});
			return;
		}
		if(!appointmentInfo.linkman) {
			Taro.showToast({
				title: "请输入姓名",
				icon: "none"
			});
			return;
		}
		if(!appointmentInfo.phone) {
			Taro.showToast({
				title: "请输入手机号",
				icon: "none"
			});
			return;
		}else if(!phoneReg.test(appointmentInfo.phone)) {
			Taro.showToast({
				title: "手机号格式不正确",
				icon: "none"
			});
			return;
		}
		if(!appointmentInfo.identity_num) {
			Taro.showToast({
				title: "请输入身份证",
				icon: "none"
			});
			return;
		}else if(!idcardReg.test(appointmentInfo.identity_num)) {
			Taro.showToast({
				title: "身份证号格式不正确",
				icon: "none"
			});
			return;
		}

		Taro.showLoading({
		    title: '请稍等...'
		});
		this.setState({ appointmenting: true });

		const dateRange = {
			start: appointmentInfo.currentDate[0],
			end: appointmentInfo.currentDate.slice(-1)[0],
			range: [...appointmentInfo.currentDate],
		};
		const params = {
			uuid: appointmentId,
			goodsUuid: goodProductUuid,
			appointmentDateRange: JSON.stringify(dateRange),
			totalNum: appointmentInfo.num,
			num: goodsProductDetail.goods_type === 2 ? appointmentInfo.currentDate.length - 1 : goodsProductDetail.late_num,
			ticketArr: appointmentInfo.code,
			linkman: appointmentInfo.linkman,
			phone: appointmentInfo.phone,
			identity_num: appointmentInfo.identity_num,
			remark: appointmentInfo.remark
		};

		const res = await newHttp.post(CONFIRM_APPOINTMENT_TT, params);
		if(res.data && res.data.uuid) {
			const { uuid } = res.data;
			Taro.hideLoading();
			this.setState({ appointmenting: false });

			Taro.showModal({
			    content: '预约成功',
				showCancel: false,
			    success: res => {
			        Taro.redirectTo({
			            // url: `/pages/order/appointment-detail?uuid=${this.uuid}`
			            url: `/main/order/order?status=55`
			        })

			    }
			})
		}else {
			this.setState({ appointmenting: false });
		}
		/*setTimeout(() => {
			this.appointmenting = false;
			Taro.hideLoading();
			Taro.showModal({
			    content: '预约成功',
				showCancel: false,
			    success: function (res) {
					console.log("跳转预约详情");
			        // Taro.redirectTo({
			        //     url: '/main/order/order?status=all'
			        // })

			    }
			})
		}, 1500)*/
	}

	// 改变购买份数
	async bindChangeByNum(val) {
		if(this.state.calculating) return;

		this.setState(state => ({
			calculating: true,
			appointmentInfo: {
				...state.appointmentInfo,
				num: val.value
			}
		}), () => {
			setTimeout(() => {
				this.setState({ calculating: false });
			}, 100);
		});
	}
	// input linkman
	handleInputLinkman = (e) => {
		this.setState(state => ({
			appointmentInfo: {
				...state.appointmentInfo,
				linkman: e.detail.value
			}
		}));
	};
	// input phone
	handleInputPhone = (e) => {
		this.setState(state => ({
			appointmentInfo: {
				...state.appointmentInfo,
				phone: e.detail.value
			}
		}));
	};
	// input idcard
	handleInputIdCard = (e) => {
		this.setState(state => ({
			appointmentInfo: {
				...state.appointmentInfo,
				identity_num: e.detail.value
			}
		}));
	};
	// input remark
	handleInputRemark = (e) => {
		this.setState(state => ({
			appointmentInfo: {
				...state.appointmentInfo,
				remark: e.detail.value
			}
		}));
	};

	render() {
		const {
			preGoodData,
			goodsProductList,
			appointmentInfo,
			dateChecking,
			uuid,
			goodsUuid,
			goodsProductDetail,
			goodProductUuid,
			calendarData,
			calculating,
			appointmenting
		} = this.state;

		return (
			<View className="appointment-make">
				<View className="apt-block goods-info">
					<Image className="img" src={preGoodData.img} />

					<View className="info-block">
						<View className="name">
							<View className="product-name">{ preGoodData.good_name }</View>
							{
								preGoodData.buy_amount && <View  className="num">x { preGoodData.buy_amount }</View>
							}
						</View>
						{
							preGoodData.good_valid_start && preGoodData.good_valid_end &&
							<View className="date">
								<Text className="sd">{ preGoodData.good_valid_start }</Text>
								<Text className="sep">至</Text>
								<Text className="ed">{ preGoodData.good_valid_end }</Text>
							</View>
						}
						<View className="price">
							<Text className="text-1 text-label">￥</Text>
							{
								preGoodData.actual_amount &&
								<Float value={preGoodData.actual_amount} />
							}
						</View>
					</View>
				</View>
				{/* 预约商品 */}
				<View className="apt-block appointment-goods">
					{
						goodsProductList.map((item, index) => (
							<View key={index} className="good-block" onClick={() => this.handleChooseGood(item)}>
								<View className="label">{ item.name }</View>
								<View className="circle">
									<View className={classnames("icon", {['active']: appointmentInfo.goodId === item.id})}>
										{/* <View></View> */}
									</View>
								</View>
							</View>
						))
					}
				</View>
				{/*预约日历*/}
				<CalendarPage
					dateChecking={dateChecking}
					uuid={uuid}
					goodsUuid={goodsUuid}
					goodsType={goodsProductDetail.goods_type}
					stayLong={goodsProductDetail.late_num}
					goodProductUuid={goodProductUuid}
					currentDate={appointmentInfo.currentDate}
					calendarData={calendarData}
					handleSureDate={this.handleSureDate}
				/>
				{/*预约日期*/}
				<View className="flex-block">
					<View>选择日期</View>
					{
						appointmentInfo.currentDate.length > 0 ?
						<View className="right">
							{
								appointmentInfo.currentDate.length > 1 ?
								<Text>{ appointmentInfo.currentDate[0] } 至 { appointmentInfo.currentDate[appointmentInfo.currentDate.length - 1] }</Text>
								:
								<Text>{ appointmentInfo.currentDate[0] }</Text>
							}
						</View>
						:
						<View className="right right-tip">请选择日期</View>
					}
				</View>
				{/*预约数量*/}
				<View className="flex-block">
					<View>数量</View>
					<View className="right">
						<AtInputNumber
							min={appointmentInfo.buy_num_min}
							max={appointmentInfo.buy_num_max}
							step={1}
							value={appointmentInfo.num}
							disabled={calculating}
							onChange={() => this.bindChangeByNum()}
							style="line-height: 0;"
						/>
					</View>
				</View>
				{/*预约码*/}
				<View className="apt-block common-info apt-form-info">
					<View className="title">券号(预约码)</View>
					<View className="oi-block">
						<View className="label label-block">
							<View>券</View>
							<View>码</View>
						</View>
						<View className="right">
							{/* <Input
								className="uni-input"
								type="number"
								:clearable="false"
								placeholder="请输入订单详情里或短信里的数字码"
								value="appointmentInfo.code"
							/> */}
							<Text>{ appointmentInfo.code }</Text>
						</View>
					</View>
				</View>
				{/*预约信息*/}
				<View className="apt-block common-info apt-form-info">
					<View className="title">预约信息</View>
					<View className="oi-block">
						<View className="label label-block">
							<View>姓</View>
							<View>名</View>
						</View>
						<View className="right">
							<Input
								className="uni-input"
								type="text"
								placeholder="请输入姓名"
								value={appointmentInfo.linkman}
								onInput={this.handleInputLinkman}
							/>
						</View>
					</View>
					<View className="oi-block">
						<View className="label label-block">
							<View>电</View>
							<View>话</View>
						</View>
						<View className="right">
							<Input
								className="uni-input"
								type="number"
								placeholder="请输入电话号码"
								cursorSpacing={40}
								maxlength={11}
								value={appointmentInfo.phone}
								onInput={this.handleInputPhone}
							/>
						</View>
					</View>
					<View className="oi-block">
						<View className="label label-block">
							<View>身</View>
							<View className="ct">份</View>
							<View>证</View>
						</View>
						<View className="right">
							<Input
								className="uni-input"
								type="identity_num"
								placeholder="请输入身份证"
								cursorSpacing={50}
								maxlength={18}
								value={appointmentInfo.identity_num}
								onInput={this.handleInputIdCard}
							/>
						</View>
					</View>
				</View>
				{/*备注*/}
				<View className="apt-block common-info apt-form-info">
					<View className="title">备注</View>
					<View className="txt-block">
						<Input
							className="uni-input"
							type="textarea"
							maxlength={200}
							placeholder="请输入备注"
							cursorSpacing={90}
							value="appointmentInfo.remark"
							onInput={this.handleInputRemark}
						/>
					</View>
				</View>

				<View className="apt-btn" onClick="appointmentNow">
					<Button type="warn" loading={appointmenting} disabled={appointmenting}>立即预约</Button>
				</View>
			</View>
		)
	}
}
